#coding=utf-8
#依赖库
#pip install requests
#pip install pygame
#pip install eyed3
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import json
import time
import requests
import pygame
import eyed3
import time

#主播房间号
roomId = 208588

#点歌关键词
pyKey = "pypy "

#点歌文件地址
file = "E:\\mileber\\diange\\diange.txt"

print "py交易开始，准备发射弹幕！"

#为了防止重复
lastSongName = ""
timeLast = ""

while 1:
    #获取弹幕并获取歌名
    keyword = ""
    admin = "【观众老爷】"
    form = {"roomid": roomId}
    f = requests.post("http://live.bilibili.com/ajax/msg", data=form)
    danmu = json.loads(f.text, encoding="utf-8")
    print danmu
    danmulist = danmu["data"]["room"]
    for danmu in danmulist[::-1]:
        if danmu["text"].encode("utf-8").find(pyKey) != -1:
            userName = danmu["nickname"].encode("utf-8")
            timeNow = danmu["timeline"].encode("utf-8")
            keyword = danmu["text"].encode("utf-8")
            keyword = keyword[keyword.find(pyKey) + len(pyKey):]
            if danmu["isadmin"] == 1:
                admin = "【黄管】"
            
            if keyword != lastSongName and timeNow > timeLast :
                print admin + userName + " 点歌 " + keyword
                with open(file,"w") as f:
                    f.write(admin + userName + " 点歌 " + keyword)
                    f.write("\n")
            break
    if keyword != "" and keyword != lastSongName and timeNow > timeLast:
        try:
            #向qq音乐请求歌曲下载地址
            url = "http://route.showapi.com/213-1"
            send_data = {
                "showapi_appid": "24166",
                "showapi_sign": "5197f4c5ac6c4df993739392d741d579",
                "keyword": keyword,
                "page": "1"
            }
            g = requests.post(url, data=send_data)
            print keyword + " 正在下载"
            with open(file,"a") as p:
                p.write(keyword + " 正在下载")
                p.write("\n")
            music = json.loads(g.text, encoding="utf-8")
            musiclist = music["showapi_res_body"]["pagebean"]["contentlist"]
            download_link = musiclist[0]["downUrl"]
            musicfile = requests.get(download_link)
            print keyword + " 下载成功"
            with open(file,"a") as q:
                q.write(keyword + " 下载成功")
                q.write("\n")
            music=open("temp.mp3","wb")
            music.write(musicfile.content)
            music.close()
            #获取音乐时间并播放
            musictime = format(eyed3.load("temp.mp3").info.time_secs)
            pygame.mixer.init()
            pygame.mixer.music.load("temp.mp3")
            pygame.mixer.music.play(loops=0, start=0.0)
            print keyword + " 正在播放"
            with open(file,"a") as t:
                t.write(keyword + " 正在播放")
                t.write("\n")
            time.sleep(float(musictime))
            pygame.mixer.music.stop()
            lastSongName = keyword
            timeLast = timeNow
            print lastSongName
            pygame.quit()
            os.remove("temp.mp3")
        except:
            pass
    #print u"等待点歌"
    with open(file,"w") as r:
        r.write("等待点歌")
        r.write("\n")
        r.write("格式： pypy 歌名")
    time.sleep(5)
